<template>
  <el-dialog :title="title" width="600px" :visible.sync="visible">
    <el-form ref="form" size="mini" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="form.sort" placeholder="请输入"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="form.status"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="mini" icon="el-icon-circle-check" @click="submitForm()">确定</el-button>
      <el-button @click="visible = false" size="mini" icon="el-icon-circle-close">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {categoryAdd, categoryUpdate, getById} from "@/api/product/category";

export default {
  data() {
    return {
      title: '',
      visible: false,
      form: {},
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    add(data) {
      this.title = '新增分类'
      this.form = {}
      this.visible = true
      if (data) {
        this.form.parentCid = data.id
        this.form.status = 1
        this.form.catLevel = data.catLevel + 1
      } else {
        this.form.parentCid = 0
        this.form.status = 1
        this.form.catLevel = 1
      }
    },

    edit(data) {
      this.title = '编辑分类'
      getById(data.id).then(res => {
        this.visible = true
        this.form = res.data
      })
    },

    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            categoryUpdate(this.form).then(() => {
              this.visible = false
              this.$emit('ok',[this.form.parentCid])
              this.$message.success('修改成功')
            })
          } else {
            categoryAdd(this.form).then(res => {
              if (res.success) {
                this.$message.success('添加成功')
                this.visible = false
                this.$emit('ok',[this.form.parentCid])
              }
            })
          }
        }
      });
    },
  }
}
</script>
